<?php defined('SYSPATH') or die('No direct script access.');
                          
class Calender_Controller extends Template_Controller 
{
	public $template = 'layout/calendar';

	public function __construct()
	{
		parent::__construct();

		$this->template->menu = '';
		$this->template->content = '';
	}
	
	public function index($month, $year)
	{
        $calendar = new Calendar($month, $year);

		$calendar->standard('today')->standard('weekends')->standard('prev-next');
		
		$event = new Calendar_Event_Model();
		
		$day = 1;
		$title = 'title_'.$this->lang;
		$content = 'content_'.$this->lang;
		
		while(true)
		{
			if( strtotime($year.'-'.$month.'-'.$day) == '' ) break;
			
			$date = $year.'-'.($month < 10 ? '0'.$month : $month).'-'.($day < 10 ? '0'.$day : $day);
			
			$result = $event->where("'".$date."' between start_date and end_date")->find_all();
			
			foreach($result as $item)
			{
				$popup = '<div class="box"><h3>'.$item->$title.'</h3>';
				$popup .= '<div class="content">'.str_replace("\n", '', $item->$content).'</div>';
				$popup .= '<div class="date">'.Kohana::lang('site.startdate').'：'.$item->start_date.'<br/>'.Kohana::lang('site.enddate').'：'.$item->end_date.'</div>';
				
				if($item->start_time != '00:00:00')
				{
					$popup .= '<div class="date">'.Kohana::lang('site.acttime').'：';
					$popup .= substr($item->start_time, 0, 5);
					$popup .= $item->end_time != '00:00:00' ? '--'.substr($item->end_time, 0, 5) : '';
				}
				
				$popup .= '</div><div>';
				
				$calendar->attach($calendar->event()
					->condition('year', $year)
					->condition('month', $month)
					->condition('day', $day)
					->output('<span style="color:#CC6633;cursor: pointer;" onmouseover="return overlib(\''.htmlspecialchars($popup).'\', WIDTH, 304);" onmouseout="return nd();">'.$item->$title.'</span>'));
			}
			
			$day++;
		}
				
		$this->template->content = $calendar->render();

	}
		
	public function create($year, $month, $day)
	{
		$model = new Calendar_Category_Model();
		$view = new View('calendar/addevents');
		$view->categories = $model->find_all();
		$view->year = $year;
		$view->month = $month;
		$view->day = $day;
		$this->template->content = $view->render();
	}
	
	public function save()
	{
		$event = new Calendar_Event_Model();
		
		$event->title = $_POST['title'];
		$event->content = $_POST['event_content'];
		$event->start_date = $_POST['start_date'];
		$event->days = $_POST['days'];
		$event->start_time = $_POST['start_time_h'].':'.$_POST['start_time_s'].':00';
		$event->end_time = $_POST['end_time_h'].':'.$_POST['end_time_s'].':00';
		$event->category_id = $_POST['category_id'];
		$event->type = ( $_POST['event_type'] == 'Once' ) ? 'Once' : $_POST['type'];
		
		$event->save();
		
		url::redirect('calender/index/'.date('n').'/'.date('Y'), 302);
	}
}